package com.example.demo.common.utills;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;


import lombok.extern.slf4j.Slf4j;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/*
 *
 * token工具
 *
 * */

@Slf4j
public class TokenUtil {

    public static final String AUTH_HEADER_KEY = "Authorization" ;
    //private static final String AUTH_HEADER_KEY = "Authorization";//定义token返回头部
    public static final String TOKEN_PREFIX = "Bearer";//token前缀15*60*1000

    private static final long EXPIRE_TIME = 24*60*60*1000;

    private static final String TOKEN_SECRET = "tokenqkj";//密钥盐


    /*
     * 生成签名
     * */
    public static String sign(String account,String userId){
        String token = null;
        try{
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);

            token = JWT.create().withIssuer("auth0").withClaim("account",account).withClaim("userId",userId).withExpiresAt(expiresAt).sign(Algorithm.HMAC256(TOKEN_SECRET));
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    /*
     * 签名验证
     * */
    public static String verify1(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("issuer: " + jwt.getIssuer());
            System.out.println("account: " + jwt.getClaim("account").asString());
            System.out.println("userId: " + jwt.getClaim("userId").asString());
            System.out.println("过期时间： " + jwt.getExpiresAt());
            return jwt.getClaim("account").asString();
        } catch (Exception e) {
            return "null";
        }

    }
    public static DecodedJWT verify(String token){
        DecodedJWT verify=null;
        try {
            verify = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build().verify(token);
        }catch (TokenExpiredException e){
            log.info("Token过期:{}", token);
            return null;
        }
        return verify;
    }


    /*
     *
     * 获取请求的token 参数：HttpServletRequest httpRequest
     * */

    public static String getRequestToken(){

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(TokenUtil.AUTH_HEADER_KEY);

//        if (StringUtils.isBlank(token)){
//            token = httpRequest.getParameter("token");
//        }
        return token;
    }
}
